﻿
Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_BanHang_Create
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Session("curSA") = Nothing
            Session("ListGenPO") = Nothing

            'Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            'If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
            '    ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            'Else
            '    Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            'End If
            txtOrderDate.Text = Now.Date.ToString("dd/MM/yyyy")
            BindListStore()
            ddlStore.Attributes.Add("onchange", "return GenerateOrderId()")
        End If

    End Sub
    Protected Sub BindListStore()
        Dim userId As Integer = Session("UserId")
        Using Data As New VSEntities
            Dim p = (From q In Data.Stores Join k In Data.UserStores On q.StoreId Equals k.StoreId Where k.UserId = userId Select q Order By q.Title).ToList

            With ddlStore
                .DataValueField = "StoreId"
                .DataTextField = "Title"
                .DataSource = p
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", ""))

            End With
        End Using
    End Sub

    Protected Sub btnSaveOrderDetail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveOrderDetail.Click

        If Session("Username") = Nothing Then
            Excute_Javascript("Alertbox('Bạn chưa đăng nhập vào hệ thống. vui lòng đăng nhập !');window.location ='../../Login.aspx';", Me.Page, True)
            Exit Sub
        End If
        Using data As New VSEntities
            'Kiem tra don hang da ton tai chua
            Dim o = (From q In data.Orders Where q.OrderId = txtMaDonHang.Text.Trim Select q).FirstOrDefault()

            If (Not o Is Nothing) Then
                Excute_Javascript("Alertbox('Số đơn hàng đã tồn tại.');", Me.Page, True)
                Exit Sub
            End If
            ' Lưu thông tin  Order

            Dim p As New VSModel.BanHang
            Try
                p.StoreId = ddlStore.SelectedValue
                p.BanHangId = txtMaDonHang.Text
                p.CustomerName = IIf(txtCustomerCode.Text <> "", txtCustomer.Text, "Không cung cấp")
                p.Address = txtAddress.Text
                p.Phone = txtPhone.Text
                p.Email = txtEmail.Text
                p.Created = Now
                p.Creator = Session("UserName")
                p.BanHangDate = StringToDate(txtOrderDate.Text)
                data.BanHangs.AddObject(p)
                data.SaveChanges()
                hidID.Value = p.Id

                'lưu thông tin cho OrderDetail
                If hidID.Value <> "0" Then
                    Try
                        Dim index As Integer = 0
                        Dim GrossAmount As Integer = 0
                        For i As Integer = 0 To hidRowIndex.Value - 1
                            Dim strMaterialCode As String = ""
                            Dim strUnit As String = ""
                            Dim intAmount As Integer = 0

                            Dim txtMaterialCode As String = "txtChoice" + i.ToString
                            If Request.Form(txtMaterialCode) <> Nothing AndAlso Request.Form(txtMaterialCode).ToString.Trim() <> "" Then
                                strMaterialCode = Request.Form(txtMaterialCode)
                            End If

                            If (strMaterialCode.Trim <> "") Then

                                Dim txtAmount As String = "txtAmount" + i.ToString
                                If Request.Form(txtAmount) <> Nothing AndAlso Request.Form(txtAmount).ToString.Trim() <> "" AndAlso Request.Form(txtAmount).ToString.Trim() <> "0" Then
                                    Try
                                        intAmount = Integer.Parse(Request.Form(txtAmount))
                                    Catch ex As Exception
                                        intAmount = 0
                                    End Try
                                End If


                                If (intAmount <> 0) Then
                                    'Luu xuong Order Detail
                                    Dim _ProductId As Integer = (From q In data.Products Where q.Code = strMaterialCode Select q.ProductId).FirstOrDefault
                                    Dim intPrice As Double = (From q In data.Products Where q.Code = strMaterialCode Select q.SellPrice).FirstOrDefault

                                    Dim od As New BanHangDetail
                                    od.BanHangId = CInt(hidID.Value)
                                    od.ProductId = _ProductId
                                    od.ProductCode = strMaterialCode
                                    od.Number = intAmount

                                    GrossAmount += intAmount * intPrice
                                    od.GrossAmount = intAmount * intPrice

                                    data.BanHangDetails.AddObject(od)

                                    data.SaveChanges()
                                    index = index + 1

                                End If
                            End If
                        Next
                        p.GrossAmount = GrossAmount
                        data.SaveChanges()
                        'logInfo = "Insert OrderDetail of Order: " & txtDoc_serial_no.Text & "<br>" & logInfo
                        ' Insert_App_Log(logInfo, Function_Name.Order, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                        Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.'); ", Me.Page, True)
                        Response.Redirect("Detail.aspx?ID=" & p.Id.ToString)


                    Catch ex As Exception

                        Excute_Javascript("Alertbox('Cập nhật chi tiết bán hàng thất bại.');", Me.Page, True)
                        Exit Sub
                    End Try
                End If
            Catch ex As Exception

                Excute_Javascript("Alertbox('Cập nhật Order thất bại.');", Me.Page, True)
            End Try
            '    End If
            'End If
        End Using
    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect("List.aspx")
    End Sub
End Class
